require("./index.scss");
require("../../common/component/checkbox.scss");
var STip = ZFT.Util.STip;
var Ajax = ZFT.Util.Ajax;
var Pagination = require("COMMON/modules/pagination-x/v1.0");
var ParseTemplate = ZFT.Util.ParseTemplate;
var Template = {
    list: ParseTemplate(require("./tpl/staffList.xtpl")),
    addStaff: ParseTemplate(require("./tpl/addStaff.xtpl")),
    setPer: ParseTemplate(require("./tpl/setPerModal.xtpl")),
    tr: ParseTemplate(require("./tpl/tr.xtpl")),
    confModal: ParseTemplate(require("./tpl/confmodal.xtpl")),
    setHouseModal: ParseTemplate(require("./tpl/setHouseModal.xtpl"))
}
var Permissioin = ZFT.Util.Class({
    container: $("body"),
    __canLoad: true,
    permissionData: [],
    init: function () {
        var _this = this;
        _this.getPermission();
    },
    EVENTS: {
        "click #staffPermission": "initStaffList",
        "keyup #keyInp": "getStaffList"
    },
    initStaffList: function (e) {
        var tar = (e) ? $(e.currentTarget) : $("#staffPermission"),
            _this = this,
            pagination,
            list = Template.list();
        if (tar.hasClass("active") && _this.__canLoad == false) return false;
        tar.addClass("active").siblings().removeClass("active");
        $("#centerContent").html(list);
        $("#getStaff").on("click", function () { _this.loadStaffList(1) });
        pagination = this.pagination = new Pagination({
            container: $(".paginationWrap"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        });
        pagination.on("page.switch", function (toPage, currentPage, totalPage) {
            pagination.render({ current: currentPage, toPage: toPage }),
                _this.loadStaffList(toPage);
        });
        _this.addNewStaff();
        _this.loadStaffList(1); //初始化

    },
    //加载员工列表
    loadStaffList: function (toPage) {
        if (!toPage) toPage = 1;
        var _this = this,
            pagination = $(".paginationWrap"),
            tbody = $("#tbody"),
            page_size = pagination.attr("data-size");
        ZFT.Util.Ajax("/r/Employee_getEmployee", {
            type: "POST",
            dataType: "json",
            params: {
                query: $("#queryInp").val(),
                page: toPage ? toPage : 1,
                page_size: page_size ? page_size : 15
            },
            loading: function () {
                var loading = '<tr><td colspan="4">加载中,请稍后...</td></tr>';
                pagination.hide();
                tbody.html(loading);
            },
            success: function (res) {
                if (res.code == 200) {
                    var html,
                        data = res.data;
                    html = Template.tr({ data: data.list });
                    tbody.html(html);
                    _this.setStaffPermission(); //设置员工菜单权限
                    _this.toggleStaffPermission();//启用或关闭员工权限
                    _this.laodStaffHousePermission();//设置员工房源范围
                    _this.pagination.render({ current: toPage, toPage: toPage, total: data.total })
                } else {
                    var err = '<tr><td colspan="4">' + res.msg + '</td></tr>';
                    tbody.html(err);
                }
                _this.__canLoad = false;

            }
        })
    },
    //获取员工的房源权限
    laodStaffHousePermission: function () {
        var _this = this;
        $("#tbody .btn-house").on("click", function (e) {
            var tarBtn = $(e.currentTarget),
                houseModal,
                id = tarBtn.attr("data-id");
            Ajax("/r/Employee_getHouseAuth", {
                type: "POST",
                dataType: "json",
                params: {
                    id: id
                },
                success: function (res) {
                    if (res.code == 200) {
                        var data = res.data;
                        _this.setStaffHousePermission(res.data,id);

                    } else {
                        return STip("fail", res.msg);
                    }
                }
            })
        })
    },
    //设置员工房源范围权限
    setStaffHousePermission: function (data,id) {
        var arr = [],
            curMenu = null, zTree_Menu = null, curExpandNode = null,
            _this = this,
            houseModal,
            setting = {
                view: {
                    showLine: true,
                    showIcon: false,
                    selectedMulti: false,
                    dblClickExpand: false
                },
                check: {
                    enable: true,
                    chkboxType: { "Y": "ps", "N": "ps" }
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    // onNodeCreated: this.onNodeCreated,
                    //beforeClick: beforeClick
                    beforeExpand: beforeExpand,
                    onExpand: onExpand,
                    onClick: onClick
                }
            };
        function beforeExpand(treeId, treeNode) {
            var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
            var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
            var zTree = $.fn.zTree.getZTreeObj("houseTree");
            for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
                if (treeNode !== treeNodeP.children[i]) {
                    zTree.expandNode(treeNodeP.children[i], false);
                }
            }
            while (pNode) {
                if (pNode === treeNode) {
                    break;
                }
                pNode = pNode.getParentNode();
            }
            if (!pNode) {
                singlePath(treeNode);
            }

        }
        function onClick(e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("houseTree");
            zTree.expandNode(treeNode, null, null, null, true);
        }
        function singlePath(newNode) {
            if (newNode === curExpandNode) return;
            var zTree = $.fn.zTree.getZTreeObj("houseTree"),
                rootNodes, tmpRoot, tmpTId, i, j, n;
            if (!curExpandNode) {
                tmpRoot = newNode;
                while (tmpRoot) {
                    tmpTId = tmpRoot.tId;
                    tmpRoot = tmpRoot.getParentNode();
                }
                rootNodes = zTree.getNodes();
                for (i = 0, j = rootNodes.length; i < j; i++) {
                    n = rootNodes[i];
                    if (n.tId != tmpTId) {
                        zTree.expandNode(n, false);
                    }
                }
            } else if (curExpandNode && curExpandNode.open) {
                if (newNode.parentTId === curExpandNode.parentTId) {
                    zTree.expandNode(curExpandNode, false);
                } else {
                    var newParents = [];
                    while (newNode) {
                        newNode = newNode.getParentNode();
                        if (newNode === curExpandNode) {
                            newParents = null;
                            break;
                        } else if (newNode) {
                            newParents.push(newNode);
                        }
                    }
                    if (newParents != null) {
                        var oldNode = curExpandNode;
                        var oldParents = [];
                        while (oldNode) {
                            oldNode = oldNode.getParentNode();
                            if (oldNode) {
                                oldParents.push(oldNode);
                            }
                        }
                        if (newParents.length > 0) {
                            zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                        } else {
                            zTree.expandNode(oldParents[oldParents.length - 1], false);
                        }
                    }
                }
            }
            curExpandNode = newNode;
        }
        function onExpand(event, treeId, treeNode) {
            curExpandNode = treeNode;
        }
        houseModal = Template.setHouseModal();
        for (var i = 0, len = data.build.length; i < len; i++) {
            arr.push({ "id": data.build[i].id, pId: 0, "name": data.build[i].name });
        }
        for (var j = 0, length = data.all.length; j < length; j++) {
            arr.push({ "id": "h_"+data.all[j].id, "pId": data.all[j].building_id, "name": data.all[j].number + "楼" + data.all[j].floor + "层" + data.all[j].room + "号", "checked": ($.inArray(data.all[j].id, data.house) !== -1) ? true : false });
        }
        $("#modal").html(houseModal);
        $.fn.zTree.init($("#houseTree"), setting, arr);
        _this.updateStaffHouse(id)
    },
    //更新员工房源范围
    updateStaffHouse:function(id){
        $("#saveBtn").on("click",function(e){
            var houseTree = $.fn.zTree.getZTreeObj("houseTree"),
                tarBtn=$(e.currentTarget),
                arr=[],
                _this=this,
                checkedData=houseTree.getCheckedNodes(true);
             for(var i=0,len=checkedData.length;i<len;i++){
                 if(checkedData[i].pId){
                 arr.push(checkedData[i].id.replace(/h_/g,""));
                 }
             }   
             if(arr.length===0) return STip("fail","请至少选中一个房源！");
            // console.log(arr.length)
             Ajax("/r/Employee_updateHouseAuth", {
                type: "POST",
                dataType: "json",
                params: {
                    id: id,
                    auth: JSON.stringify(arr)
                },
                loading: function () {
                    tarBtn.removeClass("m-btn_primary").attr("disabled");
                },
                success: function (res) {
                    if (res.code == 200) {
                        $("#modal").html("");
                        STip("success", "更新成功！");
                    } else {
                        tarBtn.addClass("m-btn_primary").removeAttr("disabled");
                        return STip("fail", res.msg);

                    }
                }
            })
        })
    },
    //启用/关闭 员工权限
    toggleStaffPermission: function () {
        var _this = this;
        $("#tbody .u-label-bt").on("click", function (e) {
            var tarBtn = $(e.currentTarget),
                confModal,
                modal = $("#modal"),
                id = tarBtn.attr("data-id"),
                status = tarBtn.attr("data-status");
            e.preventDefault();
            confModal = Template.confModal({ status: status });
            modal.html(confModal);
            $("#confBtn").on("click", function (e) {
                var tarBtn = $(e.currentTarget);
                Ajax("/r/Employee_updateStatus", {
                    type: "POST",
                    dataType: "json",
                    params: {
                        id: id,
                        status: (status == 0) ? 1 : 0
                    },
                    loading: function () {
                        tarBtn.removeClass("m-btn_primary").attr("disabled");
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            modal.html("");
                            STip("success", "更新成功！");
                            _this.loadStaffList(1);
                        } else {
                            return STip("fail", res.msg);
                        }
                    }
                })
            })
        })
    },
    //查看设置员工权限
    setStaffPermission: function () {
        var _this = this,
            setting = {
                view: {
                    // addHoverDom: addHoverDom,
                    //removeHoverDom: removeHoverDom,
                    selectedMulti: false,
                    showIcon: false
                },
                check: {
                    enable: true,
                    chkboxType: { "Y": "p", "N": "ps" }
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                edit: {
                    enable: false
                }
            }
        $("#tbody .btn-set").on("click", function (e) {
            var tarBtn = $(e.currentTarget),
                id = tarBtn.attr("data-id");
            Ajax("/r/Employee_getMemberAuth", {
                type: "POST",
                dataType: "json",
                params: {
                    id: id
                },
                success: function (res) {
                    var staffPer = (res.code == 200) ? res.data : [],
                        nodes = _this.transBackToOpt(staffPer),
                        setPerModal;
                    setPerModal = Template.setPer();
                    $("#modal").html(setPerModal);
                    $.fn.zTree.init($("#permissionTree"), setting, nodes);
                    _this.updateStaffPermission(id);
                }
            })
        })
    },

    //更新员工菜单权限
    updateStaffPermission: function (id) {
        var _this = this;
        $("#saveBtn").on("click", function (e) {
            var ztree = $.fn.zTree.getZTreeObj("permissionTree"),
                arr = [],
                tarBtn = $(e.currentTarget),
                checkedData = ztree.getCheckedNodes(true);
            for (var i = 0, len = checkedData.length; i < len; i++) {
                arr.push(checkedData[i].id);
            }
            if (!id || arr.length === 0) return STip("fail", "请至少选中一个权限！");
            Ajax("/r/Employee_updateMemberAuth", {
                type: "POST",
                dataType: "json",
                params: {
                    id: id,
                    auth: JSON.stringify(arr)
                },
                loading: function () {
                    tarBtn.removeClass("m-btn_primary").attr("disabled");
                },
                success: function (res) {
                    if (res.code == 200) {
                        $("#modal").html("");
                        STip("success", "更新成功！");
                    } else {
                        tarBtn.addClass("m-btn_primary").removeAttr("disabled");
                        return STip("fail", res.msg);

                    }
                }
            })
        });

    },
    //转换返回值为ztree的配置
    transBackToOpt: function (staffPer) {
        var _this = this,
            data = [];
        var perData = $.extend([], _this.permissionData);
        for (var i = 0, len = perData.length; i < len; i++) {
            if ($.inArray(perData[i].id, staffPer) !== -1) {
                perData[i]["checked"] = true;
            } else {
                perData[i]["checked"] = false;
            }
        }
        return perData;
    },
    //获取员工列表
    getStaffList: function (e) {
        var keyCode = e.keyCode;
        var _this = this;
        if (keyCode != 13) return false;
        _this.loadStaffList(1);
    },
    //新增员工
    addNewStaff: function () {
        var _this = this,
            addStaffModal = Template.addStaff(),
            regMobile = /^1\d{10}$/,
            reg;
        $("#addStaff").on("click", function () {
            $("#modal").html(addStaffModal);
            _this.clearChromeAutoFix();
            $("#saveBtn").on("click", function (e) {
                var name = $("#staffName").val(),
                    mobile = $("#staffMobile").val(),
                    status = ($("#staffStatus").prop("checked")) ? 1 : 0,
                    password = $("#staffPwd").val(),
                    data,
                    tarBtn = $(e.currentTarget);
                if (!$.trim(name)) return STip("fail", "用户名不为空！");
                if (!regMobile.test(mobile)) return STip("fail", "手机号格式错误！");
                if ($.trim(password).length < 6) return STip("fail", "密码格式错误！");
                data = {
                    name: name,
                    mobile: mobile,
                    status: status,
                    password: password
                }
                Ajax("/r/Employee_createEmployee", {
                    type: "POST",
                    dataType: "json",
                    params: data,
                    loading: function () {
                        tarBtn.removeClass("m-btn_primary").attr("disabled");
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            STip("success", "添加成功！");
                            $("#modal").html("");
                        } else {
                            STip("fail", res.msg);
                            tarBtn.removeAttr("disabled").addClass("m-btn_primary");
                        }
                    }
                })
            })
        })
    },
    //获取所有权限
    getPermission: function () {
        var data = [],
            _this = this;
        Ajax("/index/index/getPower", {
            type: "POST",
            dataType: "json",
            //async:false,
            success: function (res) {
                if (res.code == 200) {
                    data = res.data.menu;
                    _this.permissionData = data;
                }
            }
        })
    },
    //去除chrome浏览器自动填入
    clearChromeAutoFix: function () {
        setTimeout(function () {
            $("#staffMobile,#staffPwd").val("").css("background-color", "#fff");
            $("input:-webkit-autofill").css("-webkit-box-shadow", "0 0 0 1000px white inset");
        }, 400);
    },
});
$(function () {
    new Permissioin();
})